//
//  WmcCountdownButton.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/23.
//

import UIKit

// MARK: - [WmcCountdownButton]

class WmcCountdownButton: UIButton {
    typealias CountdownInformation = (times: [Int], isFinish: Bool)

    // Internal

    var isCountdown = true
    var second: TimeInterval = 0
    var startDate = Date()
    var timer: CADisplayLink?
    var resultClourse: ((CountdownInformation) -> Void)?

    /// 开始倒计时
    /// - Parameters:
    ///   - second: UInt
    ///   - isCountdown: Bool
    ///   - reuslt: ((CountdownInformation) -> Void)
    func countdown(second: UInt = 10, isCountdown: Bool = true, reuslt: ((CountdownInformation) -> Void)? = nil) {
        isUserInteractionEnabled = !isUserInteractionEnabled
        startDate = Date()
        self.second = TimeInterval(second)
        resultClourse = reuslt
        self.isCountdown = isCountdown

        timerClean()
        timer = CADisplayLink(target: self, selector: #selector(startCountdown))
        timer?.preferredFramesPerSecond = 1
        timer?.add(to: .main, forMode: .default)
        timer?.add(to: .main, forMode: .tracking)
    }

    // Private

    @objc
    private func startCountdown(_ sender: CADisplayLink) { countdownAction(from: startDate, isCountdown: isCountdown) }
}

// MARK: 小工具

extension WmcCountdownButton {
    /// 倒數的功能
    /// - Parameters:
    ///   - startDate: Date
    ///   - isCountdown: Bool
    private func countdownAction(from startDate: Date, isCountdown: Bool = true) {
        guard let components = countdownNumbers(from: startDate, isCountdown: isCountdown),
              let minute = components.times.first,
              let second = components.times.last else
        {
            timerClean()
            return
        }
        setTitle("\(String(format: "%02ds", second))", for: .normal)
        resultClourse?(components)
        if (components.isFinish || minute > 0) {
            setTitle("获取验证码", for: .normal)
            isUserInteractionEnabled = true
            timerClean()
        }
    }

    /// 倒数相关信息
    /// - Parameters:
    ///   - startDate: Date
    ///   - isCountdown: Bool
    /// - Returns: CountdownInformation
    private func countdownNumbers(from startDate: Date, isCountdown: Bool = true) -> CountdownInformation? {
        let second = Date() - startDate
        let countdownSecond = self.second - second
        let components = Date(timeIntervalSince1970: (isCountdown) ? countdownSecond : second)._components([.minute, .second])

        return (components, Int(countdownSecond) == 0)
    }

    /// Timer 释放
    private func timerClean() {
        timer?.invalidate()
        timer = nil
    }
}
